package ru.compft.web.validator;

import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import ru.compft.common.utils.GlobalErrors;
import ru.compft.web.beans.RoleBean;

import javax.annotation.Resource;

/**
 * User: ASUS
 * Date: 09.08.12
 * Time: 21:00
 * Валидатор для ролей
 */
@Component("roleValidator")
public class RoleValidator implements Validator {

    public static final String CODE = "code";

    @Resource(name = "messageSource")
    private MessageSource messageSource;

    @Override
    public boolean supports(Class<?> clazz) {
        return RoleBean.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        // Локализованное название поля code
        final String localizedCode = messageSource.getMessage(CODE, null, LocaleContextHolder.getLocale());

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, CODE, GlobalErrors.FIELD_REQUIRED, new String[]{localizedCode});
    }
}
